package cc.bluemc.modules.weixin.service;

import cc.bluemc.modules.weixin.entity.WxPublicAccountEntity;
import cc.bluemc.modules.weixin.entity.WxuserEntity;
import cc.bluemc.platform.comm.DataTablesPagination;
import cc.bluemc.platform.jdbctemplatetool.JdbcTemplateTool;
import cc.bluemc.platform.jdbctemplatetool.exception.NoColumnAnnotationFoundException;
import cc.bluemc.platform.jdbctemplatetool.exception.NoIdAnnotationFoundException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gson.bean.AuthorizationInfo;
import com.gson.bean.UserInfo;
import com.gson.bean.WeixinAccount;
import com.gson.oauth.Authorize3p;
import com.gson.oauth.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
*Wxuser service
*/
@Transactional(readOnly=true)
@Service("wxuserService")
public class WxuserService {
   	private Log log = LogFactory.getLog(this.getClass());
	@Autowired
	private JdbcTemplateTool jdbcTemplateTool;
	@Autowired
	private WxPublicAccountService accountService;

  
  	@Transactional(readOnly=false)
    public void save(WxuserEntity wxuser) throws Exception{
  		if(null== getByOpenidAndAppId(wxuser.getOpenid(),wxuser.getAppid())){
  			jdbcTemplateTool.save(wxuser);
  		}
    }
	@Transactional(readOnly=false)
    public int saveAndGetId(WxuserEntity wxuser) throws Exception{
    	return jdbcTemplateTool.save(wxuser,"id");
    }
	@Transactional(readOnly=false)
    public void update(WxuserEntity wxuser) throws Exception{
    	jdbcTemplateTool.update(wxuser);
    }
	@Transactional(readOnly=false)
    public void saveOrUpdate(WxuserEntity wxuser) throws Exception {
        if (null==wxuser.getId()) {
            save(wxuser);
        } else {
            update(wxuser);
        }
    }

    public WxuserEntity get(long id) throws NoIdAnnotationFoundException, NoColumnAnnotationFoundException{
    	return jdbcTemplateTool.get(WxuserEntity.class, id);
    }

    public List<WxuserEntity> getAll() {
    	String sql="SELECT * FROM t_wx_user ";
    	return jdbcTemplateTool.list(sql, null, WxuserEntity.class);
    }

	public DataTablesPagination getListOfPage(String appId,DataTablesPagination page){
		StringBuffer sql = new StringBuffer(" FROM t_wx_user WHERE 1=1 ");
		List<Object> params = new ArrayList<Object>();
		if(StringUtils.isNotBlank(appId)){
			sql.append("and appid=? ");
			params.add(appId);
		}

		int count =jdbcTemplateTool.count("SELECT count(0)"+sql, params.toArray());
		page.setiTotalRecords(count);

		sql.append(" LIMIT ?,?");
		params.add(page.getiDisplayStart());
		params.add(page.getiDisplayLength());
		List<WxuserEntity> list = jdbcTemplateTool.list("SELECT * "+sql, params.toArray(), WxuserEntity.class);
		page.setData(list);
		return page;
	}
	/**
	 * 根据openid得到微信用户 
	 * @param openid
	 * @return
	 * @throws NoIdAnnotationFoundException
	 * @throws NoColumnAnnotationFoundException
	 */
	public WxuserEntity getByOpenidAndAppId(String openid,String appId) throws NoIdAnnotationFoundException, NoColumnAnnotationFoundException{
		return jdbcTemplateTool.get(" 1=1 AND openid=? and appid=?", new Object[]{openid,appId}, WxuserEntity.class);
	}

	/**
	 * 同步微信用户数据
	 * @param appId
	 * @param userId
	 * @param nextOpenId
	 * @throws Exception
	 */
	@Transactional(readOnly=false)
	public void syncWxUser(String appId,int userId,String nextOpenId) throws Exception {
		WxPublicAccountEntity accountEntity = accountService.get(userId, appId);
		if (null!=accountEntity) {
			WeixinAccount weixinAccount = WeixinAccount.getWeixinAccount();
			AuthorizationInfo authAccessToken
					= Authorize3p.getAuthAccessToken(weixinAccount, accountEntity.getAppid(), accountEntity.getAuthorizerRefreshToken());
			JSONObject follwersList = User.getFollwersList(authAccessToken.getAuthorizer_access_token(), nextOpenId);
			JSONArray data = follwersList.getJSONObject("data").getJSONArray("openid");

			List<UserInfo> userInfos = User.batchGetuserInfo(authAccessToken.getAuthorizer_access_token(), data);
			WxuserEntity wxuserEntity;
			for(UserInfo o:userInfos){
				wxuserEntity = new WxuserEntity(o);
				wxuserEntity.setAppid(appId);
				save(wxuserEntity);
			}

			int total = follwersList.getIntValue("total");
			int count = follwersList.getIntValue("count");
			if(count<total&&total==10000){
				String next_openid = follwersList.getString("next_openid");
				syncWxUser(appId,userId,nextOpenId);
			}

		}
	}

	/**
	 * 删除
	 * @param appId
	 * @throws Exception
	 */
	@Transactional(readOnly=false)
	public void deleUserByAppId(String appId) throws Exception {
		jdbcTemplateTool.getJdbcTemplate().update("DELETE FROM t_wx_user WHERE appid=?", appId);
	}
}
